<template>
    <div class="search-select-bar" style="width:100%" @click.stop="readonlyOpen">
        <el-button  v-if="inputType==='button'" @click="handleOpen" :type="buttonType"
                    :disabled="disabled" style="width:100%" ><slot></slot></el-button>

        <el-input   v-if="inputType === 'input'"  :type="isInput ? 'text' : 'hidden'"  v-model="valueText"
                    :disabled="disabled" label-width="100px" :placeholder="placeholder"
                    :readonly="readonly" :clearable="clearable"  @clear="handleClear" >
            <template #append>
                <el-icon v-show="readonly && value && value.length && !disabled"
                         class="close-icon" @click.stop="handleClear"><error /></el-icon>
                <el-button :icon="Search" @click.stop="handleOpen" :disabled="disabled"></el-button>
            </template>
        </el-input>
        <div class="checkbox-input checkbox-input-radio" :class="{'checkbox-select-disabled': disabled }"  v-if="!isInput && inputType!=='button' && selectType === 'radio' && value">
            <div class="input-checkbox-tag"  @click.stop="handleOpen">
                <span v-if="!value" style="color:#999">请选择</span>
                {{modelValueText || value}}
                <el-icon v-if="!disabled && clearable && value"
                         class="close-icon" @click.stop="handleClear" color="#aaa"><error /></el-icon>
            </div>
            <el-button :icon="Search" class="tag-button" @click.stop="handleOpen" :disabled="disabled"></el-button>
        </div>

        <div class="checkbox-input" v-if="inputType!=='button' && selectType === 'checkbox' && value.length">
            <div class="input-checkbox-tag" v-if="!maxShowTag">
                <el-tag
                    v-for="(tag, index) in value"
                    :key="(tag, index)"
                    class="mx-1"
                    :closable="isDelTag"
                    :disable-transitions="false"
                    @close="handleClose(index)"
                >{{modelValueText[index] || tag}}</el-tag>
            </div>
            <div class="input-checkbox-tag" v-else>
                <el-tag
                    v-for="(tag, index) in maxList"
                    :key="(tag, index)"
                    class="mx-1"
                    :closable="isDelTag"
                    :disable-transitions="false"
                    @close="handleClose(index)"
                >{{modelValueText[index] || tag}}</el-tag>
                <el-tag>...</el-tag>
            </div>
            <el-button :icon="Search" class="tag-button" @click.stop="handleOpen" :disabled="disabled"></el-button>
        </div>
    </div>
</template>

<script  setup>
import { ref, watch, computed, nextTick } from 'vue';
import { useStore } from 'vuex';
import { MdInput, MdButton, MdIcon, MdTag } from 'mdesign3';
import { Error, Search } from '@mdesign3/icons-vue';
import getConfig from './config/index.js';
import MdSearchDialog from './index.js';
import MdSearchDialogPerson from './staff.js';
import { useUser } from '@/store/store';
const store = useStore();
const { userDict } = useUser();
const props = defineProps({
    type: {
        type: String,
        default: 'input',
    },
    inputType: {
        type: String,
        default: 'input',
    },
    labelWidth: {
        type: String,
        default: '',
    },
    rules: {
        type: Object,
        default: () => {
            return {};
        },
    },
    modelValue: {
        type: [String, Number, Array],
        default: '',
    },
    modelValueText: {
        type: [String, Number, Array],
        default: '',
    },
    modelItems: {
        type: [String, Number, Array],
        default: '',
    },
    modelKey: {
        type: String,
        default: ''
    },
    modelText: {
        type: String,
        default: '',
    },
    disabled: {
        type: Boolean,
        default: false,
    },
    placeholder: {
        type: String,
        default: '请选择',
    },
    selectType: {
        type: String,
        default: 'radio',
    },
    data: {
        type: Object,
        default: () => {
            return {};
        },
    },
    readonly: {
        type: Boolean,
        default: false,
    },
    paramKeys: {
        type: Array,
        default: () => [],
    },
    clearable: {
        type: Boolean,
        default: true,
    },
    buttonType: {
        type: String,
        default: 'text',
    },
    beforeMounted: {
        type: Function,
        default: () => true,
    },
    enterpriseNo: { // 是否传入企业编码
        type: Boolean,
        default: false,
    },
    maxShowTag: {
        type: Number,
        default: null,
    },
    isDelTag: {
        type: Boolean,
        default: true,
    },
    dialogType: {
        type: String,
        default: 'normal',
    },
    // 绑定的参数
    params: {
        type: Object,
        default: () => {
            return {};
        },
    },
    afterEachList: {
        type: Function,
        default: (value) => {
            return value;
        },
    },
    modelEvent: {
        type: String,
        default: '',
    },
    searchType: {
        type: String,
        default: 'select'
    },
    title: {
        type: String,
        default: ''
    },
    disabledPage: {
        type: Boolean,
        default: false
    }
});

const eventKey =['A','B', 'C', 'D', 'E', 'F'];
const emit = defineEmits(['select',
    'confirm',
    'update:modelItems',
    'update:modelValue',
    'clear',
    'update:modelValueText',
    'update:modelA',
    'update:modelB',
    'update:modelC',
    'update:modelD',
    'update:modelE',
    'update:modelF',
]);

const value = ref(props.modelValue);
const valueText = ref(props.modelValueText);
const maxList = computed(() => {
    return value.value.slice(0, 3);
});
watch(() => props.modelValue, (n) => {
    if (value.value === n) return;
    value.value = n;
});
watch(() => props.modelValueText, (n) => {
    valueText.value = n;
});
watch(() => value.value, (n) => {
    emit('update:modelValue', n);
});
watch(() => valueText.value,  (n) => {
    emit('update:modelValueText', n);
});

const isInput = computed(() => {
    if (props.inputType === 'input') {

        if (props.selectType === 'checkbox' && value.value.length > 0) {
            return false;
        }

        if (props.selectType === 'radio' && value.value && props.readonly) {
            return false;
        }

        return true;
    }

    return false;
});


function readonlyOpen() {
    props.readonly && handleOpen();
}

// 发送定义的事件
function sendEmit(obj) {
    if (!props.modelEvent) return;
    if (!obj) {
        const arr = props.modelEvent.split(',');
        arr.forEach((item, index) => {
            if (props.selectType === 'checkbox' && value.value.length > 0) {
                emit(`update:model${eventKey[index]}`, []);
                return;
            }
            emit(`update:model${eventKey[index]}`, '');
        });
        return;
    }
    if (Array.isArray(obj)) {
        const arr = props.modelEvent.split(',');
        const res = [];
        obj.forEach((item, index) => {
            arr.forEach(sub => {
                res.push(sub, item[sub]);
            });
        });
        arr.forEach((item, index) => {
            emit(`update:model${eventKey[index]}`, res[item]);
        });
        return;
    };
    const arr = props.modelEvent.split(',');
    arr.forEach((item, index) => {
        emit(`update:model${eventKey[index]}`, obj[item]);
    });
}

function handleOpen() {
    if (props.disabled) {
        return;
    }

    if (!props.beforeMounted()) {
        return;
    }
    setTimeout(() => {
        const options = getConfig(props.type, store.state.dictsArray);
        options.selectType = props.selectType;
        options.modelValue = props.modelValue;
        options.modelValueText = props.modelValueText;
        options.modelItems = props.modelItems;
        options.afterEachList = props.afterEachList;
        options.searchType = props.searchType;
        options.title = props.title || options.title;
        options.url = options.url.replace('{tenantCode}', userDict.value.tenantCode);
        options.params = {
            ...options.params,
            ...props.params,
        }
        props.paramKeys.forEach((item) => {
            options.params[item] = props.data[item];
        });

        if (props.dialogType === 'staff') {
            handleClear();
            MdSearchDialogPerson(options, (res) => {
                if (options.selectType  === 'radio') {
                    value.value = res[0][options.modelKey];
                    valueText.value =  res[0][options.modelText];
                    emit('update:modelItems',  res[0]);
                    emit('change', res[0]);
                    sendEmit(res[0])
                    return;
                }
                value.value = res.map( item => item[options.modelKey]);
                valueText.value = res.map( item => item[options.modelText]);
                emit('update:modelItems', res);
                emit('change', res);
                sendEmit(res)
            });
            return;
        }

        MdSearchDialog(options, (res) => {
            handleClear();
            nextTick(() => {
                    if (options.selectType  === 'radio') {
                    value.value = res[0][options.modelKey];
                    valueText.value = res[0][options.modelText];
                    emit('update:modelItems',  res[0]);
                    emit('change', res[0]);
                    sendEmit(res[0])
                    return;
                }
                value.value = res.map( item => item[options.modelKey]);
                valueText.value = res.map( item => item[options.modelText]);
                emit('update:modelItems', res);
                emit('change', res);
                sendEmit(res)
            })
           
        });
    });
}


function handleClear() {
    emit('update:modelValue',  null);
    if (props.selectType === 'radio') {
        emit('update:modelValueText', '');
    } else {
        emit('update:modelValueText', []);
    }
    emit('clear');
    sendEmit(null);
}

function handleClose(index) {
    value.value.splice(index, 1);
    valueText.value.splice(index, 1);
    if (props.modelItems) {
        props.modelItems.splice(index, 1);
    }
}

</script>
<style lang="less" scoped>
.close-icon {
    position: absolute;
    left: -20px;
    top: 50%;
    transform:translateY(-50%);
    cursor: pointer;
}
.input-checkbox-tag {
    position: relative;
    .close-icon {
        right: 8px;
        left: 100%;
        transform:translateY(-50%) translatex(-15px);
    }
}
.checkbox-input-radio {
    .input-checkbox-tag {
        line-height: 22px;
        .close-icon {
            display: none;
        }
        &:hover{
            .close-icon {
                display: block;
            }
        }
    }
}
.checkbox-input {
    display:flex;
    border-radius: 5px;
    width: 100%;
    align-items: stretch;
}

.input-checkbox-tag {
    min-height: 24px;
    flex: 1;
    border: 1px solid #c4cdd5;
    box-sizing: border-box;
    padding: 0px 5px;
    &:hover {
        border-color: #aaa;
    }
    &:active {
        border-color:#0077ff;
    }
}
.tag-button {
    border-left: none;
    width: 42px;
    background-color: var(--el-bg-color);
    height: auto;
}

.checkbox-select-disabled {
    .input-checkbox-tag {
        border-width: 0;
    }
}


</style>
